package de.devcity.storeretrieve;

import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class Store {

	// Most of the program happily stolen from http://hc.apache.org/httpcomponents-client-ga/examples.html
	public static void main(String[] args) throws Exception {
		if (args.length < 3)  {
			System.out.println("Usage: store 'URL to upload to' 'ForeignId' 'Path to file' ['Path to next file' ...]");
			System.exit(1);
		}

		String URL = args[0]; //"https://roland:91GUqlt03ulwHXZmwSTwZcEpboRPiRTn@devcity.de:8443/storeretrieve/upload.jsp"
		String ForeignId = args[1];
		ArrayList<String> files = new ArrayList<String>();
		for(int i = 2; i < args.length; i++) {
			files.add(args[i]);
		}
		
		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpPost httppost = new HttpPost(URL);
			
			MultipartEntity reqEntity = new MultipartEntity();
			reqEntity.addPart("press", new StringBody("Upload"));
			reqEntity.addPart("origin", new StringBody("upload"));
			if(!ForeignId.equals(""))
				reqEntity.addPart("ForeignId", new StringBody(ForeignId));

			int idx = 0;
			for(String file : files) {
				FileBody bin = new FileBody(new File(file));
				reqEntity.addPart("file" + idx, bin);
				idx++;
			}
			
			httppost.setEntity(reqEntity);

			System.err.print("Uploading: ");
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			System.err.println(response.getStatusLine());
			if (resEntity != null) {
				StringWriter writer = new StringWriter();
				IOUtils.copy(resEntity.getContent(), writer, "UTF-8");
				String textResponse = writer.toString();

				Pattern p; Matcher m;

				p = Pattern.compile("<!-- RESULT: (.+)? -->");
				m = p.matcher(textResponse);
				if (m.find()) {
				    System.err.println("Result: " + m.group(1));
				}
				
				p = Pattern.compile("<!-- COUNT: (.+)? -->");
				m = p.matcher(textResponse);
				if (m.find()) {
				    System.err.println("Count: " + m.group(1));
				}
				
				p = Pattern.compile("<!-- ID: (.+)? -->");
				m = p.matcher(textResponse);
				if (m.find()) {
				    System.out.println(m.group(1));
				}
			} else {
				System.err.println("No result. ERROR.");
			}
			EntityUtils.consume(resEntity);
		} finally {
			try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
		}
	}
}

